#include "nvpanel.h"
#include <iostream>


NvPanel::NvPanel(QObject *parent)
{
    timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &NvPanel::updateUtilization);
    timer->start(1000);

    // 初始化NVML
    nvmlReturn_t result = nvmlInit();
    if (result != NVML_SUCCESS) {
        std::cerr << "Failed to initialize NVML: " << nvmlErrorString(result) << std::endl;
    }
}

NvPanel::~NvPanel()
{
    if (timer != nullptr)
    {
        if (timer->isActive())
        {
            timer->stop();
        }
    }
    // 关闭NVML
    nvmlShutdown();
}

QString NvPanel::getGpuName() const {
    char name[NVML_DEVICE_NAME_BUFFER_SIZE];
    nvmlDevice_t device;
    nvmlReturn_t result = nvmlDeviceGetHandleByIndex(0, &device);
    if (result == NVML_SUCCESS) {
        result = nvmlDeviceGetName(device, name, NVML_DEVICE_NAME_BUFFER_SIZE);
        if (result == NVML_SUCCESS) {
            return QString(name);
        }
    }
    return QString("Unknown GPU");
}

QString NvPanel::getGpuUtilization() const {
    unsigned int gpuUtilization = 0;
    nvmlDevice_t device;
    nvmlReturn_t result = nvmlDeviceGetHandleByIndex(0, &device);
    if (result == NVML_SUCCESS) {
        nvmlUtilization_t utilization;
        result = nvmlDeviceGetUtilizationRates(device, &utilization);
        if (result == NVML_SUCCESS) {
            gpuUtilization = utilization.gpu;
        }
    }
    return QString::number(gpuUtilization) + "%";
}

QString NvPanel::getMemoryUtilization() const {
    unsigned int memoryUtilization = 0;
    nvmlDevice_t device;
    nvmlReturn_t result = nvmlDeviceGetHandleByIndex(0, &device);
    if (result == NVML_SUCCESS) {
        nvmlUtilization_t utilization;
        result = nvmlDeviceGetUtilizationRates(device, &utilization);
        if (result == NVML_SUCCESS) {
            memoryUtilization = utilization.memory;
        }
    }
    return QString::number(memoryUtilization) + "%";
}

void NvPanel::updateUtilization() {
    emit utilChanged();
}

